<?php

namespace App\Http\Controllers\Steel;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Steel\SteelArchive as SteelSteelArchive;
use App\Jobs\Inventory;
use App\Models\Order\Saleorder;
use App\Models\Order\Saleordersub;
use App\Models\Purchase\PurchaseOrderSub;
use App\Models\Steel\SteelArchive;
use App\Models\Steel\SteelAttrList;
use App\Models\Steel\SteelType;
use App\Models\Stock\Stock as StockStock;
use App\Services\Chanjet\ChanjetRequest;
use Illuminate\Http\Request;

use Maatwebsite\Excel\Facades\Excel;
use App\Services\Common\CommonExcelExport;
use App\Services\Common\DownloadTemp;
use App\Services\Stock\Stock;
use Illuminate\Support\Facades\DB;
use function Symfony\Component\Translation\t;

/**
 * 钢材档案相关
 */
class SteelArchiveController extends BaseController
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        //需获取当前用户所属账套
        $status = $request->status ?? 0;
        $isgetall = $request->isgetall ?? 0;
        $list = SteelArchive::getList($request, $this->mangerinfo['cpid'], $status, $isgetall);
        $config_arr = config('steelconfig.steel_type_2');
        foreach($list['list'] as &$val){

            if (in_array($val['material_name'], $config_arr)) {
                $val['is_red'] = 2;
            } else {
                $val['is_red'] = 1;
            }
        }


        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 新增档案
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['archive_no', 'archive_name', 'archive_spec', 'type_id', 'subtype_id', 'breed_id', 'material_id', 'steel_factory_id', 'archive_type']);

        $Validate = new SteelSteelArchive;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $isexist = SteelArchive::where([['cpid', $this->mangerinfo['cpid']], ['archive_no', $req_data['archive_no']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '档案编码不允许重复']);
        }

        //校验各属性是否存在
        $type_info = SteelType::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['type_id']])->first();
        if (!$type_info) {
            return response()->json(['code' => '001', 'msg' => '分类参数错误']);
        }

        $subtype_info = SteelType::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['subtype_id'], 'pid' => $req_data['type_id']])->first();
        if (!$subtype_info) {
            return response()->json(['code' => '001', 'msg' => '子分类参数错误']);
        }


        $breed_info = SteelAttrList::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['breed_id'], 'type_id' => 1])->first();
        if (!$breed_info) {
            return response()->json(['code' => '001', 'msg' => '品种参数错误']);
        }

        $material_info = SteelAttrList::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['material_id'], 'type_id' => 2])->first();
        if (!$material_info) {
            return response()->json(['code' => '001', 'msg' => '材质参数错误']);
        }

        $steel_factory_info = SteelAttrList::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['steel_factory_id'], 'type_id' => 3])->first();
        if (!$steel_factory_info) {
            return response()->json(['code' => '001', 'msg' => '钢厂参数错误']);
        }
        if (!in_array($req_data['archive_type'], [1, 2, 3, 4])) {
            return response()->json(['code' => '001', 'msg' => '无效码单类型']);
        }
        $archive_spec = explode('*', $req_data['archive_spec']);
        if ($req_data['archive_type'] == 1) {
            if (count($archive_spec) < 2) {
                return response()->json(['code' => '001', 'msg' => '无效规格参数']);
            } else {
                if (!(isset($archive_spec[0]) && $archive_spec[0] > 0) || !(isset($archive_spec[1]) && $archive_spec[1] > 0)) {
                    return response()->json(['code' => '001', 'msg' => '无效规格参数']);
                }
            }
        }


        if ($req_data['archive_type'] == 3) {
            if (count($archive_spec) != 3) {
                return response()->json(['code' => '001', 'msg' => '无效规格参数']);
            } else {
                if (!(isset($archive_spec[0]) && $archive_spec[0] > 0) || !(isset($archive_spec[1]) && $archive_spec[1] > 0) || !(isset($archive_spec[2]) && $archive_spec[2] > 0)) {
                    return response()->json(['code' => '001', 'msg' => '无效规格参数']);
                }
            }
        }

        $data = [
            'cpid' => $this->mangerinfo['cpid'],
            'archive_no' => $req_data['archive_no'],
            'archive_name' => $req_data['archive_name'],
            'archive_spec' => $req_data['archive_spec'],
            'type_id' => $req_data['type_id'],
            'type_name' => $type_info['type_name'],
            'subtype_id' => $req_data['subtype_id'],
            'subtype_name' => $subtype_info['type_name'],
            'type_no' => $type_info['type_no'],
            'subtype_no' => $subtype_info['type_no'],
            'breed_id' => $req_data['breed_id'],
            'breed_name' => $breed_info['attr_val_name'],
            'material_id' => $req_data['material_id'],
            'material_name' => $material_info['attr_val_name'],
            'steel_factory_id' => $req_data['steel_factory_id'],
            'steel_factory_name' => $steel_factory_info['attr_val_name'],
            'archive_type' => $req_data['archive_type'],
            'update_at' => time()
        ];
        $data['create_at'] = time();

        DB::beginTransaction();
        try {

            $insert_id = SteelArchive::create($data)->id;

            Stock::syncStockBySteelArchive($insert_id, $data, $this->mangerinfo['cpid']);


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '新增失败' . $e->getMessage()]);
        }

        /**
         *   新增钢材档案/存货新增
         *
         *
         **/
//        if (TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
//            ChanjetRequest::getInstance()->inventoryCreate([
//                "dto" => [
//                    "Code" => $req_data['archive_no'],
//                    "Name" => $req_data['archive_name'],
//                    "Specification" => $req_data["archive_spec"],
//                    "DynamicPropertyKeys"=>["pubuserdefnvc1","pubuserdefnvc2","pubuserdefnvc3","priuserdefnvc1"],
//                    "DynamicPropertyValues" => [$steel_factory_info['attr_val_name'],$breed_info['attr_val_name'],$material_info['attr_val_name'],$archive_type_arr[strval($req_data['archive_type'])-1]],//archive_type
//
//                    "InventoryClass" => [
//                        "Code" => $subtype_info['type_no'],
//                        "Name" => $subtype_info['type_name'],
//                    ],
//                    //"Unit" => ["Code" => "001", "Name" => "吨"], //主计量单位编码
//                    "Unit" => ["Name" => "吨/件"], //主计量单位编码
//                    "SubUnitByReport" => ["Name" => "件"],
//                    "IsSingleUnit" => "false",
//                    "UnitType"=> ["Code" => "01"],
//                    "UnitGroup" => [
//                        "Name" => "吨/件"
//                    ],
//                    "IsPurchase" => "true", //存货属性：外购属性
//                    "IsSale" => "true", //存货属性：销售属性
//                    "ValueType" => [ //计价方式编码
//                        "Code" => "00"
//                    ],
//                    "TaxRate" => ["Name" =>""],
//                ]
//            ], $this->mangerinfo['org_id']);
        //}
        $archive_type_arr = ['理计', '过磅', '定尺', '虚拟']; //1理计、2过磅、3定尺
        $chanjet_param = [
            "dto" => [
                "Code" => $req_data['archive_no'],
                "Name" => $req_data['archive_name'],
                "Specification" => $req_data["archive_spec"],
                "DynamicPropertyKeys"=>["pubuserdefnvc1","pubuserdefnvc2","pubuserdefnvc3","priuserdefnvc1"],
                "DynamicPropertyValues" => [$steel_factory_info['attr_val_name'],$breed_info['attr_val_name'],$material_info['attr_val_name'],$archive_type_arr[strval($req_data['archive_type'])-1]],//archive_type

                "InventoryClass" => [
                    "Code" => $subtype_info['type_no'],
                    "Name" => $subtype_info['type_name'],
                ],
                //"Unit" => ["Code" => "001", "Name" => "吨"], //主计量单位编码
                "Unit" => ["Name" => "吨/件"], //主计量单位编码
                "SubUnitByReport" => ["Name" => "件"],
                "IsSingleUnit" => "false",
                "UnitType"=> ["Code" => "01"],
                "UnitGroup" => [
                    "Name" => "吨/件"
                ],
                "IsPurchase" => "true", //存货属性：外购属性
                "IsSale" => "true", //存货属性：销售属性
                "ValueType" => [ //计价方式编码 和华坤客户沟通过，使用先进先出2025.06.27
                    "Code" => "03",//"00":全月平均 "01":移动平均  "03":先进先出 "04":个别计价
                ],
                "TaxRate" => ["Name" =>"0"],
            ]
        ];
        $requestData = [
            "api" => "inventoryCreate",
            "param" => $chanjet_param,
            "mangerinfo" => $this->mangerinfo,
        ];
        Inventory::dispatch($requestData);

        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 删除
     */
    public function dodel(Request $request)
    {

        $id = $request->id ?? 0;
        $info = SteelArchive::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        //查询此钢材分类是否已经被使用；钢材档案和钢材子分类都不能使用；
        if($this->checkuse($info))
        {
            return response()->json(['code' => '001', 'msg' => '此钢材档案已被使用']);
        }

        $res = SteelArchive::where([['id', $id]])->delete();

        if ($res)
        {
            return response()->json(['code' => '000', 'msg' => '操作成功']);
        }else{
            return response()->json(['code' => '001', 'msg' => '操作失败']);
        }
    }



    /**
     * 修改档案
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id','archive_no', 'archive_name', 'archive_spec', 'type_id', 'subtype_id', 'breed_id', 'material_id', 'steel_factory_id', 'archive_type']);

        $Validate = new SteelSteelArchive;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $info = SteelArchive::where([['id', $req_data['id']], ['cpid', $this->mangerinfo['cpid']]])->first();

        // 新增：校验archive_no唯一性（排除当前记录）
        $existingArchive = SteelArchive::where([['archive_no', $req_data['archive_no']], ['cpid', $this->mangerinfo['cpid']]])
            ->where('id', '!=', $req_data['id'])
            ->first();

        if ($existingArchive) {
            return response()->json(['code' => '001', 'msg' => '档案编码已存在，不能重复']);
        }

        //查询此钢材分类是否已经被使用；钢材档案和钢材子分类都不能使用；
        if($this->checkuse($info))
        {
            return response()->json(['code' => '001', 'msg' => '此钢材档案已被使用']);
        }
        //校验各属性是否存在
        $type_info = SteelType::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['type_id']])->first();
        if (!$type_info) {
            return response()->json(['code' => '001', 'msg' => '分类参数错误']);
        }

        $subtype_info = SteelType::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['subtype_id'], 'pid' => $req_data['type_id']])->first();
        if (!$subtype_info) {
            return response()->json(['code' => '001', 'msg' => '子分类参数错误']);
        }


        $breed_info = SteelAttrList::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['breed_id'], 'type_id' => 1])->first();
        if (!$breed_info) {
            return response()->json(['code' => '001', 'msg' => '品种参数错误']);
        }

        $material_info = SteelAttrList::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['material_id'], 'type_id' => 2])->first();
        if (!$material_info) {
            return response()->json(['code' => '001', 'msg' => '材质参数错误']);
        }

        $steel_factory_info = SteelAttrList::where(['cpid' => $this->mangerinfo['cpid'], 'id' => $req_data['steel_factory_id'], 'type_id' => 3])->first();
        if (!$steel_factory_info) {
            return response()->json(['code' => '001', 'msg' => '钢厂参数错误']);
        }
        if (!in_array($req_data['archive_type'], [1, 2, 3, 4])) {
            return response()->json(['code' => '001', 'msg' => '无效码单类型']);
        }
        $archive_spec = explode('*', $req_data['archive_spec']);
        if ($req_data['archive_type'] == 1) {
            if (count($archive_spec) < 2) {
                return response()->json(['code' => '001', 'msg' => '无效规格参数']);
            } else {
                if (!(isset($archive_spec[0]) && $archive_spec[0] > 0) || !(isset($archive_spec[1]) && $archive_spec[1] > 0)) {
                    return response()->json(['code' => '001', 'msg' => '无效规格参数']);
                }
            }
        }


        if ($req_data['archive_type'] == 3) {
            if (count($archive_spec) != 3) {
                return response()->json(['code' => '001', 'msg' => '无效规格参数']);
            } else {
                if (!(isset($archive_spec[0]) && $archive_spec[0] > 0) || !(isset($archive_spec[1]) && $archive_spec[1] > 0) || !(isset($archive_spec[2]) && $archive_spec[2] > 0)) {
                    return response()->json(['code' => '001', 'msg' => '无效规格参数']);
                }
            }
        }

        $data = [
            'archive_name' => $req_data['archive_name'],
            'archive_spec' => $req_data['archive_spec'],
            'archive_no' => $req_data['archive_no'],
            'type_id' => $req_data['type_id'],
            'type_name' => $type_info['type_name'],
            'subtype_id' => $req_data['subtype_id'],
            'subtype_name' => $subtype_info['type_name'],
            'type_no' => $type_info['type_no'],
            'subtype_no' => $subtype_info['type_no'],
            'breed_id' => $req_data['breed_id'],
            'breed_name' => $breed_info['attr_val_name'],
            'material_id' => $req_data['material_id'],
            'material_name' => $material_info['attr_val_name'],
            'steel_factory_id' => $req_data['steel_factory_id'],
            'steel_factory_name' => $steel_factory_info['attr_val_name'],
            'archive_type' => $req_data['archive_type'],
            'update_at' => time()
        ];

        DB::beginTransaction();
        try {

            SteelArchive::where(['id'=>$info->id])->update($data);

            Stock::syncStockBySteelArchiveUp($info->id, $data, $this->mangerinfo['cpid']);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '修改失败' . $e->getMessage()]);
        }

        /**
         *   修改钢材档案/存货修改
         *
         *
         **/
        $archive_type_arr = ['理计', '过磅', '定尺', '虚拟']; //1理计、2过磅、3定尺
        $chanjet_param = [
            "dto" => [
                "Code" => $req_data['archive_no'],
                "Name" => $req_data['archive_name'],
                "Specification" => $req_data["archive_spec"],
                "DynamicPropertyKeys"=>["pubuserdefnvc1","pubuserdefnvc2","pubuserdefnvc3","priuserdefnvc1"],
                "DynamicPropertyValues" => [$steel_factory_info['attr_val_name'],$breed_info['attr_val_name'],$material_info['attr_val_name'],$archive_type_arr[strval($req_data['archive_type'])-1]],//archive_type
                "InventoryClass" => [
                    "Code" => $subtype_info['type_no'],
                    "Name" => $subtype_info['type_name'],
                ],
            ]
        ];
        $requestData = [
            "api" => "inventoryUpdate",
            "param" => $chanjet_param,
            "mangerinfo" => $this->mangerinfo,
        ];
        Inventory::dispatch($requestData);

        return response()->json(['code' => '000', 'msg' => '修改成功']);
    }


    private function checkuse($info)
    {
        //库存不能对比 因为新增的时候增加了为0的库存数据
        //目前牵扯的有销售订单；销货单；出库单；采购订单；进货单；入库单；
        //
        $isexist = Saleordersub::where([['archive_no', $info->archive_no]])->exists();
        if ($isexist) {
            return true;
        }

        $isexist = PurchaseOrderSub::where([['archive_no', $info->archive_no]])->exists();
        if ($isexist) {
            return true;
        }
        return false;
    }
    /**
     * 冻结
     */
    public function changestatus(Request $request)
    {

        $id = $request->id ?? 0;
        $info = SteelArchive::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        //存在库存则无法冻结
        $count = StockStock::where([['cpid', $this->mangerinfo['cpid']], ['steel_archive_id', $id]])
            ->where(function ($query) {
                $query->where([['can_use_weight', '<>', 0]])->orWhere([['current_pieces', '<>', 0]])
                    ->orWhere([['locked_weight', '<>', 0]])->orWhere([['locked_pieces', '<>', 0]]);
            })->count();
        if ($count > 0) {
            return response()->json(['code' => '001', 'msg' => '库存存在在库或者已锁定的库存，无法冻结']);
        }

        $status = 2;
        StockStock::where([['cpid', $this->mangerinfo['cpid']], ['steel_archive_id', $id]])->update(['status' => $status]);
        SteelArchive::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 模板下载
     */
    public function dodownload(Request $request)
    {

        $cpid = $this->mangerinfo['cpid'];

        $breed_arr = SteelAttrList::where(['cpid' => $cpid, 'status' => 1, 'type_id' => 1])->pluck('attr_val_name')->toArray();
        $material_arr = SteelAttrList::where(['cpid' => $cpid, 'status' => 1, 'type_id' => 2])->pluck('attr_val_name')->toArray();
        $steel_factory_arr = SteelAttrList::where(['cpid' => $cpid, 'status' => 1, 'type_id' => 3])->pluck('attr_val_name')->toArray();
        $row = [['分类编码', '钢材分类', '子分类编码', '子钢材分类', '钢材编码', '钢材名称', '规格', '品种','材质','钢厂','码单类型']];
        $options = [

            'H' => $breed_arr,
            'I' => $material_arr,
            'J' => $steel_factory_arr,
            'K' => ['理计', '过磅','定尺','虚拟'],
        ];
        $datawith = [
            'A' => '20',
            'B' => '20',
            'C' => '20',
            'D' => '20',
            'E' => '20',
            'F' => '20',
            'G' => '20',
            'H' => '20',
            'I' => '20',
            'J' => '20',
            'K' => '20',
        ];
        $filename = '钢材档案导入模板.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);

    }

    /**
     * 上传导入，先调用uploadfile,返回地址调用该接口
     */
    public function doimport(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'];
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];
            //处理上传的数据

            $archive_type_arr = ['理计' => 1, '过磅' => 2, '定尺' => 3, '虚拟' => 4]; //1理计、2过磅、3定尺
            //分类
            $steeltype = SteelType::where(['cpid' => $cpid, 'status' => 1])->get()->toArray();
            $steeltype_arr = [];
            foreach ($steeltype as $val) {
                $steeltype_arr[$val['type_no']] = $val;
            }
            //品种
            $breed_arr = SteelAttrList::where(['cpid' => $cpid, 'status' => 1, 'type_id' => 1])->pluck('id', 'attr_val_name')->toArray();
            //材质
            $material_arr = SteelAttrList::where(['cpid' => $cpid, 'status' => 1, 'type_id' => 2])->pluck('id', 'attr_val_name');

            //钢厂
            $steel_factory_arr = SteelAttrList::where(['cpid' => $cpid, 'status' => 1, 'type_id' => 3])->pluck('id', 'attr_val_name');
            $success_count = 0;
            $fail_count = 0;

            $dtos = []; //存货创建 批量

            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    continue;
                }
                $isexist = SteelArchive::where([['archive_no', $val[4]], ['cpid', $cpid]])->first();
                if ($isexist) { //如有已存在编号，则跳过
                    $fail_count++;
                    continue;
                }
                if (isset($steeltype_arr[$val[0]])) {
                    $type_id = $steeltype_arr[$val[0]]['id'];
                    $type_name = $steeltype_arr[$val[0]]['type_name'];
                    $type_no = $steeltype_arr[$val[0]]['type_no'];
                    if (isset($steeltype_arr[$val[2]]) && $steeltype_arr[$val[2]]['pid'] == $steeltype_arr[$val[0]]['id']) {
                        $subtype_id = $steeltype_arr[$val[2]]['id'];
                        $subtype_name = $steeltype_arr[$val[2]]['type_name'];
                        $subtype_no = $steeltype_arr[$val[2]]['type_no'];
                    } else { //分类不存在，则跳过
                        $fail_count++;
                        continue;
                    }
                } else { //分类不存在，则跳过
                    $fail_count++;
                    continue;
                }
                if (!isset($breed_arr[$val[7]])) {
                    $fail_count++;
                    continue;
                }

                if (!isset($material_arr[$val[8]])) {
                    $fail_count++;
                    continue;
                }

                if (!isset($steel_factory_arr[$val[9]])) {
                    $fail_count++;
                    continue;
                }
                if (!isset($archive_type_arr[$val[10]])) {
                    $fail_count++;
                    continue;
                }


                $data = [
                    'cpid' => $this->mangerinfo['cpid'],
                    'archive_no' => $val[4],
                    'archive_name' => $val[5],
                    'archive_spec' => $val[6],
                    'type_id' => $type_id,
                    'type_name' => $type_name,
                    'subtype_id' => $subtype_id,
                    'subtype_name' => $subtype_name,
                    'type_no' => $type_no,
                    'subtype_no' => $subtype_no,
                    'breed_id' => $breed_arr[$val[7]],
                    'breed_name' => $val[7],
                    'material_id' => $material_arr[$val[8]],
                    'material_name' => $val[8],
                    'steel_factory_id' => $steel_factory_arr[$val[9]],
                    'steel_factory_name' => $val[9],
                    'archive_type' => $archive_type_arr[$val[10]],
                    'create_at' => time(),
                    'update_at' => time()
                ];

                $dtos[] = [
                    "Code" => $val[4],
                    "Name" => $val[5],
                    "Specification" => $val[6], //存货规格
                    "DynamicPropertyKeys" => ["pubuserdefnvc1", "pubuserdefnvc2", "pubuserdefnvc3"], //钢厂 品种 材质
                    "DynamicPropertyValues" => [$val[9], $val[7], $val[8]],
                    "InventoryClass" => [
                        "Code" => $subtype_no,
                        "Name" => $subtype_name,
                    ],
                    "Unit" => ["Name" => "吨/件"], //主计量单位编码
                    "SubUnitByReport" => ["Name" => "件"],
                    "IsSingleUnit" => "false",
                    "UnitType"=> ["Code" => "01"],
                    "UnitGroup" => [
                        "Name" => "吨/件"
                    ],
                    "IsPurchase" => "true", //存货属性：外购属性
                    "IsSale" => "true", //存货属性：销售属性
                    "ValueType" => [ //计价方式编码
                        "Code" => "00"
                    ],
                ];

                DB::beginTransaction();
                try {

                    $insert_id = SteelArchive::create($data)->id;

                    Stock::syncStockBySteelArchive($insert_id, $data, $this->mangerinfo['cpid']);
                    $success_count++;

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    $fail_count++;
                    // return response()->json(['code' => '001', 'msg' => '新增失败' . $e->getMessage()]);
                }
            }

            /**
             *  批量创建 存货
             *
             */
            $ChanjetParams = [
                "dtos" => $dtos
            ];
            if (TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
                ChanjetRequest::getInstance()->inventoryCreateBatch($ChanjetParams, $this->mangerinfo['org_id']);
            }

            return response()->json(['code' => '000', 'msg' => '数据导入成功：' . $success_count . '失败：' . $fail_count]);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $list = SteelArchive::getList($request, $this->mangerinfo['cpid'], 0, 1);
        $archive_type_arr = [1 => '理计', 2 => '过磅', 3 => '定尺', 4 => '虚拟'];
        $exceldata = [];
        $row = [
            [
                'id' => '序号',
                'type_no' => '分类编码',
                'type_name' => '钢材分类',
                'subtype_no' => '子分类编码',
                'subtype_name' => '子钢材分类',
                'archive_no' => '钢材编码',
                'archive_name' => '钢材名称',
                'archive_spec' => '规格',
                'breed_name' => '品种',
                'material_name' => '材质',
                'steel_factory_name' => '钢厂',
                'archive_type' => '码单类型',
                'status' => '状态',
            ]
        ];
        foreach ($list['list'] as $key => $val) {
            $row[] = [
                'id' => $key + 1,
                'type_no' => $val['type_no'],
                'type_name' => $val['type_name'],
                'subtype_no' => $val['subtype_no'],
                'subtype_name' => $val['subtype_name'],
                'archive_no' => $val['archive_no'],
                'archive_name' => $val['archive_name'],
                'archive_spec' => $val['archive_spec'],
                'breed_name' => $val['breed_name'],
                'material_name' => $val['material_name'],
                'steel_factory_name' => $val['steel_factory_name'],
                'archive_type' => $archive_type_arr[$val['archive_type']],
                'status' => $val['status'] == 1 ? '正常' : '冻结',
            ];
        }

        $datawith = [];
        $filename = '钢材档案导出.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }

    /***
     *  获取钢材规格
     *
    */
    public function getarchivespec(Request $request){
        //archive_spec
        $mangerinfo = $this->mangerinfo;

        $archive_spec_list = SteelArchive::where(['cpid' => $mangerinfo['cpid']])->select(['archive_spec'])->get();

        if($archive_spec_list->isEmpty()){
            $archive_spec_list = [];
        }else{
            $archive_spec_list = $archive_spec_list->toArray();
            $archive_spec_list = array_unique(array_column($archive_spec_list,'archive_spec'));
        }
        $archive_spec_list = array_filter($archive_spec_list,function($spec){
            if ($spec != '') return true;
        });
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $archive_spec_list]);
    }
}
